package com.bpms.common;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
/**
 * 读取properties文件，并放入内存中
 * @author menlin
 *
 */
public class PropertyReader {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(PropertyReader.class);

	private String propertiesFileName = "";
	private HashMap map = new HashMap();

	/**
	 * 把propertiesFileName读取出来,把key的值value存入map
	 * 
	 * @param propertiesFileName
	 *            属性文件名称
	 */
	private PropertyReader(String propertiesFileName) {
		if (propertiesFileName == null) {
			propertiesFileName = "null";
			return;
		}
		this.propertiesFileName = propertiesFileName;
		int i = propertiesFileName.lastIndexOf(".properties");
		if (i == -1)
			return;
		String resourceName = propertiesFileName.substring(0, i);
		ResourceBundle bundle = null;
		try {
			bundle = ResourceBundle.getBundle(resourceName);
		} catch (MissingResourceException e) {
			logger.error("PropertyReader(String)", e); 

			return;
		}
		Enumeration e = bundle.getKeys();
		HashMap mapFromBundle = new HashMap();
		String key;
		// 把key属性value存入map
		for (; e.hasMoreElements(); mapFromBundle.put(key, bundle
				.getString(key))) {
			key = (String) e.nextElement();
		}
		map = mapFromBundle;
	}

	/**
	 * 返回propertiesFileName属性PropertyHolder(如:com/resources/ApplicationResources.properties)
	 * 
	 * @param propertiesFileName
	 * @return PropertyHolder
	 */
	public static PropertyReader getHolder(String propertiesFileName) {
		return new PropertyReader(propertiesFileName);
	}

	public String getString(String key) {
		Object obj = map.get(key);
		return (String) obj;
	}

	public void setValue(String key, String value, String weburl) {
		try {

			OutputStream fos = new FileOutputStream(propertiesFileName);
			map.put(key, value);
			// property.store(fos, "Update " + key + " value");
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			logger.error("setValue(String, String, String)", e);  

			System.out.println("FileNotFoundException");
		} catch (IOException e) {
			logger.error("setValue(String, String, String)", e);  

			System.out.println("IOException");
		}
	}


}
